package day11;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Cache {
    Map<String,Object> map=new HashMap<>();
    ReentrantReadWriteLock rwlock=
            new ReentrantReadWriteLock();
    public void get(String key){
        try {
            String name=Thread.currentThread().getName();
            rwlock.readLock().lock();
            Object value=null;
            System.out.println(name+"开始读取数据1S数据:"+key+","+value);
            value=map.get(key);
            Thread.sleep(1000);
            System.out.println(name+"结束读取数据1S数据:"+key+","+value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwlock.readLock().unlock();
        }
    }
    public void put(String key,Object value){
        try {
            String name=Thread.currentThread().getName();
            rwlock.writeLock().lock();
            System.out.println(name+"开始写入1S数据"+key+","+value);
            map.put(key,value);
            Thread.sleep(1000);
            System.out.println(name+"结束写入1S数据"+key+","+value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwlock.writeLock().unlock();
        }
    }
    public static void main(String[] args) {
        Cache c=new Cache();
        Random r=new Random();
        for(int i=0;i<6;i++){
            int temp=i;
            new Thread(()->{
                for(int j=0;j<3;j++) {
                    if (r.nextInt(2) == 0) {
                        c.get("key" + temp);
                    } else {
                        c.put("key" + temp, "value" + temp);
                    }
                }
            },"线程:"+i).start();
        }
    }
}
